package com.ala.libmodbusapi;

import android.util.Log;

public class ModbusOperatio {

    String TAG = "ModbusOperatio";
    libmodbusapi mLibmodbusapi;

    String devserial = "/dev/ttymxc2";
    int devband = 115200;

    int BUSID = 1;

    String strDevPara="";

    public static ModbusOperatio newInstance(String devserial, int devband) {
        return new ModbusOperatio(devserial, devband);
    }

    public ModbusOperatio(String devserial, int devband) {
        this.devserial = devserial;
        this.devband = devband;
    }

    public int initDev(){
        mLibmodbusapi = new libmodbusapi();
        int fid = mLibmodbusapi.init_modbus(devserial, BUSID, devband, 8, 1, 'N',4000, 4000);
        if(fid == 0) {
            Log.i(TAG, " init modbus success Jni Version = " + mLibmodbusapi.getVersion());
        }else {
            Log.i(TAG, " init modbus fail . fid = " + fid);
        }
        return fid;
    }


    public int md_led_1_open(int newAddr){
        return mLibmodbusapi.modbus_write_register(newAddr, 10, 0xff);
    }

    public int md_led_1_close(int newAddr){
        return mLibmodbusapi.modbus_write_register(newAddr, 10, 0);
    }

    public int md_set_addr(int newAddr, int type){
        return mLibmodbusapi.modbus_write_register(newAddr, 3, type);
    }

    public int md_lig_para(int newAddr, int type){
        return mLibmodbusapi.modbus_write_register(newAddr, 11, type);
    }

    public int md_up_time(int newAddr){
        int devTime[]=new int[7];
        return mLibmodbusapi.modbus_write_registers(newAddr, 20, devTime.length, devTime);
    }


    public int md_query_dev(int newAddr){
        int devPara[]=new int[50];
        int ret= mLibmodbusapi.modbus_read_registers(newAddr, 0, devPara.length, devPara);
        if(ret==-1){
            strDevPara="查询失败";
        }else{
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append("\n 软硬件版本" + devPara[1] + "-" + devPara[2]);
            stringBuffer.append("\n 回路1 -" + (devPara[10]==0?"关":"开"));
            stringBuffer.append("\n 回路1亮度 -" + devPara[11]);

            stringBuffer.append("\n 电表初始化 -" + devPara[30]);
            stringBuffer.append("\n 电压 -" + devPara[31] + " V");
            stringBuffer.append("\n 电流 -" + (devPara[32]*0.001) + " A");
            stringBuffer.append("\n 功率 -" + devPara[33] + " w");
            stringBuffer.append("\n 电量 -" + (devPara[36]*1000+devPara[37]+devPara[38]*0.01) + " Kwh");

            strDevPara = stringBuffer.toString();
        }
        return ret;
    }

    public String getStrDevPara() {
        return strDevPara;
    }
}
